package spring.boot.initializer.impl;

import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.ReflectionUtils;
import spring.boot.initializer.MyWebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @ClassName MySpringServletContainerInitializer
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/3/10 11:30
 * @Version 1.0
 **/
@HandlesTypes(MyWebApplicationInitializer.class)
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
        List<MyWebApplicationInitializer> initializers = new LinkedList<>();
        if (webAppInitializerClasses != null) {
            for (Class<?> waiClass : webAppInitializerClasses) {
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        MyWebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((MyWebApplicationInitializer)
                                ReflectionUtils.accessibleConstructor(waiClass).newInstance());
                    } catch (Throwable ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            return;
        }
        for (MyWebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);
        }
    }
}
